<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.jpg" mode="aspectFill"></image>

    <view class="bar-box" :style="{ marginTop: titleMargin + 'px' }">
      <image class="back" src="/static/images/back.png" @click="back"></image>
      <view class="title">服务详情</view>
    </view>

    <view class="do-box">
      <view class="vip" style="justify-content: center">{{ info.name }}</view>
      <scroll-view scroll-y enable-flex class="content" :style="applet_version != 1 ? 'height: 70vh' : ''">
        <rich-text space="nbsp" :nodes="info.content"></rich-text>
      </scroll-view>
      <block v-if="applet_version == 1">
        <view class="vip" v-if="coupon_price">
          <view>原价：{{ info.price }}元</view>
          <view>可用优惠券：{{ coupon_price }}元抵扣</view>
        </view>
        <view class="btn" @click="openService">{{ info.price - coupon_price }}元立即开通</view>
      </block>
    </view>

    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{ mobile }}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>

    <!-- 购买服务成功提示弹框 START -->
    <view v-if="authModal" class="modal-overlay">
      <view class="modal" @click.stop>
        <view class="modal-content">
          <image class="close" src="/static/images/close.png" @click="closeAuthModal"></image>
          <scroll-view scroll-y enable-flex class="photos-box" style="margin-top: 80rpx;max-height: calc(70vh - 80rpx);">
            <rich-text space="nbsp" :nodes="authArticle"></rich-text>
          </scroll-view>
        </view>
      </view>
    </view>
    <!-- 购买服务成功提示弹框 END -->
  </view>
</template>

<script>
import http from '@/utils/http'
import app from '@/App.vue'

export default {
  computed: {
    app() {
      return app
    }
  },
  data() {
    return {
      titleMargin: 0, // 动态顶部间距
      info: [],
      coupon_price: 0,
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《喜来啦隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
      authModal: false,
      authArticle: '',
      applet_version: -1
    };
  },
  created() {
    this.setDynamicMargin(); // 设置动态间距
  },

  onLoad: function (options) {
    this.$http.post('/index/Api/getAppletVersion').then(res => {
      this.applet_version = parseInt(res.data.data);
    })

    var id = options.id;
    this.$http.post('/index/Api/serviceDetail', {id}).then(res => {
      if (res.data.result === 1) {
        var {info, coupon_price} = res.data.data;

        info.price = parseFloat(info.price);
        coupon_price = parseFloat(coupon_price);

        this.info = info;
        this.coupon_price = coupon_price;
      } else {
        this.$common.doErrorResult(res);
      }
    })

    this.$http.post('/index/Api/getAuthArticle', {type: 2}).then(res => {
      this.authArticle = res.data.data;
    })
  },

  methods: {
    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    closeAuthModal: function () {
      this.authModal = false;
    },

    back: function () {
      uni.navigateBack();
    },


    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    getPhoneNumber: function (e) {
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        } else {
          this.$common.doErrorResult(res)
        }
      })
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;
                    this.userCenter(user_id, scene_user_id)
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

    userCenter: function (user_id, scene_user_id = 0) {
      this.$http.post('/index/Api/userCenter', {user_id, scene_user_id}).then(res => {
        if (res.data.result === 1) {
          this.info = res.data.data

          // 存储认证状态
          uni.setStorageSync('rz_status', res.data.data.rz_status)

          if (res.data.data.up_user_id > 0) uni.removeStorageSync('scene_user_id');
        } else {
          this.$common.doErrorResult(res);
        }
      })
    },

    openService: function () {
      var user_id = uni.getStorageSync('user_id'),
        service_id = this.info.id,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）

      if (!user_id) {
        uni.showLoading({
          title: '自动登录中...',
          mask: true
        })

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
              uni.hideLoading();
              if (res.data.result === 1) {
                var user_id = res.data.data;
                uni.setStorageSync('user_id', user_id)
                var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;

                this.userCenter(user_id, scene_user_id)
                this.openService();
              } else {
                this.show_login = true;
              }
            })
          }
        })
      } else {
        if (long_time > 3) {
          //将当前时间戳存为缓存
          uni.setStorageSync('timestamp', timestamp / 1000);

          uni.showLoading({
            title: '服务开通中...',
            mask: true
          })

          this.$http.post('/index/Api/openService', {user_id, service_id}).then(res => {
            uni.removeStorageSync('timestamp');
            if (res.data.result == 1) {
              var {order_sn, pay_data} = res.data.data;
              /********主要代码********/
              if (pay_data) {
                uni.getProvider({
                  service: 'payment',
                  success: result => {
                    var provider = result.provider;
                    if (provider) {
                      uni.requestPayment({
                        provider: provider,
                        orderInfo: {order_sn},
                        timeStamp: pay_data.timeStamp,
                        nonceStr: pay_data.nonceStr,
                        package: pay_data.package,
                        signType: pay_data.signType,
                        paySign: pay_data.paySign,
                        _debug: 1,
                        success: res => {
                          uni.hideLoading();
                          this.authModal = true;
                        },
                        fail: function (res) {
                          uni.showToast({
                            title: '取消支付',
                            icon: 'none'
                          })
                        }
                      })
                    } else {
                      uni.showToast({
                        title: '取消支付',
                        icon: 'none'
                      })
                    }
                  }
                });
              }
              /********主要代码********/
            } else {
              uni.hideLoading();
              this.$common.doErrorResult(res);
            }
          })
        }
      }
    },
  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;

  button{
    border: none;
    padding: 0;
    margin: 0;
  }

  .do-box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 90%;
    height: 85vh;
    margin-top: 40rpx;

    .vip {
      width: calc(100% - 40rpx);
      padding: 40rpx 10rpx;
      font-size: 38rpx;
      background: #FCD4CE;
      border-radius: 30rpx;
      text-align: center;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .content {
      width: calc(100% - 40rpx);
      height: 54vh;
      background: #fff;
      border-radius: 20rpx;
      padding: 20rpx;
    }

    .btn {
      width: 100%;
      padding: 20rpx 0;
      background: #F30E0E;
      color: #fff;
      font-size: 36rpx;
      border-radius: 20rpx;
      text-align: center;
    }
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;

    .modal {
      width: 80%;

      .modal-content {
        position: relative;
        background: #fff;
        padding: 20rpx;
        border-radius: 20rpx;
        max-height: 70vh;

        .close {
          position: absolute;
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          right: 20rpx;
          top: 20rpx;
        }

        .photos-box {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          width: 100%;
          margin-top: 130rpx;
          max-height: calc(70vh - 130rpx);

          .show-box {
            position: relative;
            width: 48%;
            margin-bottom: 10rpx;

            &:nth-last-child(1),
            &:nth-last-child(2) {
              margin-bottom: 0;
            }

            .photo {
              width: 100%;
              height: 260rpx;
            }
          }
        }
      }
    }
  }

}
</style>

